package component.dom4j.quickstart;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Foo {
	
	public Document parse(URL url) throws DocumentException{
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(url);
		return document;
	}
	
	public void bar(Document document) throws IOException{
		
		Element root = document.getRootElement();
		int index = 0;
		for(Iterator i = root.elementIterator();i.hasNext();){
			
			
			Element out = (Element)i.next();
			out.addAttribute(new QName("ADDR"), ""+index++);
			out.addElement("NO").addText(""+index++);
		}
		XMLWriter writer = new XMLWriter(
            new FileWriter( "e:/test1.xml" )
        );
        writer.write( document );
        writer.close();


        // Pretty print the document to System.out
        OutputFormat format = OutputFormat.createPrettyPrint();
        writer = new XMLWriter( System.out, format );
        writer.write( document );

        // Compact format to System.out
        format = OutputFormat.createCompactFormat();
        writer = new XMLWriter( System.out, format );
        writer.write( document );
	}

	@Test
	public void testFoo() throws DocumentException, IOException{
		bar(new SAXReader().read(new File("E:\\test.xml")));
	}
}
